﻿#include "apiprovider.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QFileInfo>
#include <QStandardPaths>
#include <QGuiApplication>
#include <QUrl>
#include <qwindowsmanager.h>

ApiProvider::ApiProvider(QObject *parent) : QObject(parent)
{  
    QString path =QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);

    m_configDir = QDir(path);
    if(!m_configDir.exists()){
        m_configDir.mkpath(path);
    }

    m_appPath = QCoreApplication::applicationFilePath();
}

QJsonArray ApiProvider::readListItem(QString name)
{
    QFile file(m_configDir.path() + "/"+ name+ ".json");
    if(file.exists()){
        if(file.open(QFile::ReadOnly)){
            QByteArray bytes  = file.readAll();
            QJsonParseError err;
            QJsonDocument doc = QJsonDocument::fromJson(bytes,&err);
            if(err.error == QJsonParseError::NoError){
                if(doc.isArray()){
                    return doc.array();
                }
            }

            file.close();
        }
    }

    return QJsonArray();
}

void ApiProvider::saveListItem(QString name, QJsonArray items)
{
    QFile file(m_configDir.path() + "/"+ name + ".json");
    if(file.open(QFile::WriteOnly | QFile::Text)){
        QJsonDocument doc(items) ;
        file.write(doc.toJson());
        file.flush();
        file.close();
    }
}

QJsonObject ApiProvider::readAppConfig()
{
    QFile file(m_configDir.path() + "/app.json");
    if(file.exists()){
        if(file.open(QFile::ReadOnly)){
            QByteArray bytes  = file.readAll();
            QJsonParseError err;
            QJsonDocument doc = QJsonDocument::fromJson(bytes,&err);
            if(err.error == QJsonParseError::NoError){
                if(doc.isObject()){
                    return doc.object();
                }
            }

            file.close();
        }
    }

    return QJsonObject();
}

void ApiProvider::saveAppConfig(QJsonObject obj)
{
    QFile file(m_configDir.path() + "/app.json");
    if(file.open(QFile::WriteOnly | QFile::Text)){
        QJsonDocument doc(obj) ;
        file.write(doc.toJson());
        file.flush();
        file.close();
    }

    bool autoStart = obj.value("autoStart").toBool(false);
    m_appPath.replace("/","\\");
    QWindowsManager::setAutoStartEnabled("ToDoer",m_appPath,autoStart);
}
